package com.wt.activiti.service;

import com.wt.activiti.listener.MyEventListener;
import com.wt.activiti.response.TaskResoponse;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author: wangtao
 * @Date:8:38 2017/6/30
 * @Email:tao8.wang@changhong.com
 */
@Service
public class SimpleService {

    //注入为我们自动配置好的服务
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    public void startProcess(String key) {
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("processId", key);
        // 添加一次监听器，所有都可用
//        ntruntimeService.addEveListener(new MyEventListener());
        runtimeService.startProcessInstanceByKey(key, variables);
    }

    //获得某个人的任务别表
    public List<TaskResoponse> getTasks(String assignee) {
        System.out.println("存在代理人的任务在其他人的任务列表是不可见的");
        List<Task> tasks = taskService.createTaskQuery().taskCandidateUser(assignee).list();
        System.out.println("候选人任务列表CandidateUser:" + tasks.size());
        if (tasks.size() == 0) {
            tasks = taskService.createTaskQuery().taskAssignee(assignee).list();
            System.out.println("代理人任务列表taskAssignee:" + tasks.size());
        }
        List<TaskResoponse> dtos = new ArrayList<TaskResoponse>();
        for (Task task : tasks) {
            dtos.add(new TaskResoponse(task.getId(), task.getName()));
        }
        return dtos;
    }

    //完成任务
    public void completeTasks(Boolean joinApproved, String taskId) {
        Map<String, Object> taskVariables = new HashMap<String, Object>();
        taskVariables.put("joinApproved", joinApproved);
        taskService.complete(taskId, taskVariables);
    }


    public void printMsg(DelegateExecution execution) {
        System.out.println("method simpleService.printMsg(execution)");
        Map<String, Object> variables = execution.getVariables();
        System.out.println("variables=" + variables);
    }

    //用户任务候选人指定的时候，会在执行到用户任务时才执行该方法。因此，再用户任务还未被执行到之前，可以动态设置候选人
    public String getUsers() {
        System.out.println("getUsers");
        return "wt";
    }

    public void complete(String taskId) {
        taskService.complete(taskId);
    }
}
